package com.own.component.common.util.executor;

import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * ContextCopyingDecorator
 *
 * @author chenxueli
 * @date 2022-12-02 09:58:00
 */
@SuppressWarnings("all")
public class ContextCopyingDecorator implements TaskDecorator {

    @Override
    public Runnable decorate(Runnable runnable) {
        // 或当前线程的上下文
        var attributes = getCurrentRequestAttributes();
        var contextMap = MDC.getCopyOfContextMap();
        return () -> {
            try {
                // 设置新线程的上下文信息
                if (attributes != null) {
                    RequestContextHolder.setRequestAttributes(attributes);
                }
                if (contextMap != null) {
                    MDC.setContextMap(contextMap);
                }
                runnable.run();
            } finally {
                // 重置新线程的上下文信息
                RequestContextHolder.resetRequestAttributes();
                MDC.clear();
            }
        };
    }

    public RequestAttributes getCurrentRequestAttributes() {
        try {
            return RequestContextHolder.currentRequestAttributes();
        } catch (Exception e) {
            return null;
        }
    }

}
